package com.example.util;

import java.io.*;

/**
 * @Classname FileUtils
 * @Description TODO
 * @Date 2023/4/25 22:39
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class FileUtils {

    public static void wirteBytesByPath(byte[] bytes,String path){
        File file1=new File(path);
        InputStream in=null;
        FileOutputStream fos =null;
        try {
            in=new ByteArrayInputStream(bytes);
            fos=new FileOutputStream(file1);
            byte[] b = new byte[1024];
            while ((in.read(b)) != -1) {
                // 写入数据
                fos.write(b);
            }
            fos.flush();
            fos.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fos!=null){
                try {
                    fos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte[] getBytesByPath(String path){
        File file = new File(path);
        FileInputStream inputStream=null;
        ByteArrayOutputStream baos=null;
        try {
            inputStream=new FileInputStream(file);
            baos = new ByteArrayOutputStream();
            byte buff[] = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) != -1) {
                baos.write(buff, 0, len);
            }
            baos.flush();
            byte[] bytes= baos.toByteArray();
            return bytes;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if(baos!=null){
                try {
                    baos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
